// 学习获取网站标签爬取数据
const https = require("https")
const cheerio = require('cheerio') // jquery 得一个库

const  fs = require('fs') // 文件库
const axios = require('axios')
const { resolve } = require('path') // 路径
const { reject } = require('assert') // 断言

const express = require('express')
// const bodyParser = require("body-parser")
const app = express()
const cors = require('cors');
// app.use(bodyParser.json());
app.use(cors())

console.log(123)


// function getUrl(url) {
//     const savePath = './image'
//     let imgOrgin = url.split('/')[url.split('/').length - 1];
//     let newUrl = ''
//     axios.get(url, {responseType: 'arraybuffer'}).then(res => {
//         const img = Buffer.from(res.data, 'binary')
//         fs.writeFile(`${savePath}/${imgOrgin}`, res.data, 'binary', (err) => {
//             if (err) {
//                 throw err
//             } else {
//                 console.log(`下载成功`);
//                 newUrl = `${savePath}/${imgOrgin}`
//             }
//             console.log(newUrl, 4444)
//             return newUrl
//         })

//     })
// }
// 获取展示的图片








// console.log(getUrl('https://img3.doubanio.com/view/photo/s_ratio_poster/public/p480747492.jpg'), 47)
app.get('/getList', (req,res) => {
    let html = ''
    let list = []
    https.get('https://movie.douban.com/top250?start=0&filter=', (res1) => {
        res1.on('data', (chunk) => {
            html += chunk
        })

        res1.on('end', () => {
            const $ = cheerio.load(html)

            $('li .item').each(function() {
                const title = $('.title', this).text() +  $('.other', this).text()
                const star = $('.info .bd .rating_num', this).text()
                const pic = $('.pic img', this).attr('src')
                const desc = $('.info .bd p', this).text()
                list.push({
                    title: title,
                    star: star,
                    pic: pic,
                    desc: desc
                })
            })
            res.send({data: list})
//             // fs.writeFile('./newData.json', JSON.stringify(list),(res,err)=> {
//             //     if (err) {
//             //         throw err
//             //     }
//             //     console.log('文件保存成功');
//             // })
        })
    })
})


app.listen(3001, () => {
    console.log('Server started on port 3000');
  });